<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar,
  NSelect,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

defineOptions({ name: '预约列表' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'
import {router} from "@/router";

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '预约列表',
  initForm: {},
  doCreate: api.createAppointmentList,
  doUpdate: api.updateAppointmentList,
  doDelete: api.deleteAppointmentList,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  option_type:[],
  option_dtype:[],
  option_space:[]
})
onMounted(() => {
  api.getAppointmentType().then((res) => (data.option_type = res.data))
  api.getSettingProjectList().then((res) => (data.option_dtype = res.data))
  api.getSpaceList().then((res) => (data.option_space = res.data))
  $table.value?.handleSearch()
})

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '状态',
    key: 'status_name',
    width: 30,
    align: 'center',
    render(row) {
      return h(
        NTag,
        { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
        { default: () => row.status_name }
      )
    },
  },
  // {
  //   title: '预约类型',
  //   key: 'type_name',
  //   width: 60,
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  //   render(row) {
  //     return h(
  //       NTag,
  //       { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
  //       { default: () => row.type_name }
  //     )
  //   },
  //
  // },
  // {
  //   title: '子类型',
  //   key: 'd_type_name',
  //   width: 60,
  //   align: 'center',
  //   fixed: 'left',
  //   ellipsis: { tooltip: true },
  //   render(row) {
  //     return h(
  //       NTag,
  //       { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
  //       { default: () => row.d_type_name }
  //     )
  //   },
  // },
  {
    title: '门店',
    key: 'space_name',
    align: 'center',
    width: 60,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
        NTag,
        { type: 'primary', size: 'small', bordered: false, style: { margin: '2px 3px' } },
        { default: () => row.space_name }
      )
    },
  },
    {
    title: '对象',
    key: 'designer_name_s',
    align: 'center',
    width: 40,
  }, {
    title: '项目',
    key: 'project_name_s',
    align: 'center',
    width: 60,
    render(row) {
      return h(
        'div',
        {
          style: { whiteSpace: 'pre-line' }, // 允许换行
        },
        `${row.project_name}\n(${row.ex_names})` // 使用换行符分隔
      );
    }
  },{
    title: '人数',
    key: 'come_nums',
    align: 'center',
    width: 20,
    // ellipsis: { tooltip: true },
  },
    {
    title: '预约人',
    key: 'user_name',
    align: 'center',
    width: 60,
    render(row) {
      return h(
        'div',
        {
          style: { whiteSpace: 'pre-line' }, // 允许换行
        },
        `${row.user_name}\n${row.user_phone}` // 使用换行符分隔
      );
    },
},

    {
    title: '预约时间',
    key: 'time',
    align: 'center',
    width: 80,
    // ellipsis: { tooltip: true },
  },
    {
    title: '关联单号',
    key: 'order_id',
    align: 'center',
    width: 50,
    // ellipsis: { tooltip: true },
  },{
    title: '时长(分)',
    key: 'longs',
    align: 'center',
    width: 50,
    // ellipsis: { tooltip: true },
  },

  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      if(row.status==3){}else{
        return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handle_pass(row,1)
              },
            },
            {
              default: () => '通过',
              icon: renderIcon('material-symbols:check', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/content/contents/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handle_pass(row,2),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '驳回',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/contents/delete']]
              ),
            default: () => h('div', {}, '确定驳回该数据吗?'),
          }
        ),
      ]
      }

    },
  },
]

async function handle_pass(row,status) {
  row.status = status
  await api.updateAppointmentList(row)
  $table.value?.handleSearch()
}

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}
async function  on_excel(){
   await api.onAppointmentExcel({start_time:queryItems.value.start_time,end_time:queryItems.value.end_time})
   data.show_excel = true
   //$message?.success('正在生成下载文件,请前往下载中心查看')
}
function go_excel(){
  router.push({ path: '/downloads/list' });
}
</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent>
      <CommonPage show-footer title="预约列表">
        <template #action>
          <NButton v-permission="'get/api/appointment/list/excel'" class="float-right" type="primary" @click="on_excel">
            <TheIcon icon="material-symbols:timeline" :size="18" class="mr-5" />导出
          </NButton>

        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getAppointmentList"
          :scroll-x="1600"
        >
          <template #queryBar>
            <QueryBarItem label="预约类型" :label-width="80">
              <NSelect
                v-model:value="queryItems.type"
                style="width: 150px"
                :options="data.option_type"
                clearable
                placeholder="请选类型"
              />
            </QueryBarItem>
<!--            <QueryBarItem label="预约子类" :label-width="80">-->
<!--              <NSelect-->
<!--                v-model:value="queryItems.d_type"-->
<!--                style="width: 150px"-->
<!--                :options="data.option_dtype"-->
<!--                clearable-->
<!--                placeholder="请选类型"-->
<!--              />-->
<!--            </QueryBarItem>-->
            <QueryBarItem label="预约门店" :label-width="80">
              <NSelect
                v-model:value="queryItems.space_id"
                style="width: 150px"
                :options="data.option_space"
                clearable
                placeholder="请选预约门店"
              />
            </QueryBarItem>
            <QueryBarItem label="预约时间" :label-width="70">
              <NDatePicker
                v-model:value="datetimeRange"
                type="datetimerange"
                clearable
                placeholder="请选择时间范围"
                @update:value="handleDateRangeChange"
              />
            </QueryBarItem>
          </template>
        </CrudTable>

<n-modal
      v-model:show="data.show_excel"
      preset="dialog"
      title="导出提示..."
      content="导出文件正在生成中,是否前去下载中心下载"
      positive-text="立即查看"
      negative-text="过会再去"
      @positive-click="go_excel"
      @negative-click="cancelCallback"
    />
      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
